﻿<script lang="ts" name="systransferorder" setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import type { FormRules } from "element-plus";
import { formatDate } from '/@/utils/formatTime';
import { useSystransferorderApi } from '/@/api/OutWarehou/systransferorder';
import { useGoodsModelApi } from '/@/api/Goods/Details/goodsModel';
import { useWarehouseModelApi } from '/@/api/interacting/warehouse/warehouseModel';

//父级传递来的函数，用于回调
const emit = defineEmits(["reloadTable"]);
const systransferorderApi = useSystransferorderApi();
const goodsModelApi = useGoodsModelApi();
const warehouseModelApi = useWarehouseModelApi();
const ruleFormRef = ref();

const state = reactive({
	title: '',
	loading: false,
	showDialog: false,
	ruleForm: {} as any,
	stores: {},
	dropdownData: {} as any,
	goodsList: [] as any[],
	warehouseList: [] as any[]
});

// 自行添加其他规则
const rules = ref<FormRules>({
  code: [{required: true, message: '请选择调拨单号！', trigger: 'blur',},],
  documentStatus: [{required: true, message: '请选择单据状态！', trigger: 'change',},],
  applyDate: [{required: true, message: '请选择调拨申请日期！', trigger: 'change',},],
  outStatus: [{required: true, message: '请选择出库状态！', trigger: 'change',},],
  inStatus: [{required: true, message: '请选择入库状态！', trigger: 'change',},],
  transferQuantity: [{required: true, message: '请选择调拨数量！', trigger: 'blur',},],
});

// 加载货品列表
const loadGoodsList = async () => {
	try {
		const res = await goodsModelApi.page({ pageSize: 10000, page: 1 });
		if (res.data.result && res.data.result.items) {
			state.goodsList = res.data.result.items;
		}
	} catch (error) {
		console.error('加载货品列表失败:', error);
	}
};

// 加载仓库列表
const loadWarehouseList = async () => {
	try {
		const res = await warehouseModelApi.page({ pageSize: 10000, page: 1 });
		if (res.data.result && res.data.result.items) {
			state.warehouseList = res.data.result.items;
		}
	} catch (error) {
		console.error('加载仓库列表失败:', error);
	}
};

// 页面加载时
onMounted(async () => {
	await loadGoodsList();
	await loadWarehouseList();
});

// 根据货品编码获取货品名称（如果已经是名称则直接返回）
const getGoodsNameByCode = (goodsCodeOrName: string) => {
	if (!goodsCodeOrName) return '';
	// 先尝试按goodsCode匹配
	const goods = state.goodsList.find(item => item.goodsCode === goodsCodeOrName);
	// 如果找到了，返回名称；如果没找到，可能已经是名称了，直接返回
	return goods ? goods.goodsName : goodsCodeOrName;
};

// 根据货品名称获取货品编码（如果已经是编码则直接返回，如果无法转换则保持原值）
const getGoodsCodeByName = (goodsName: string) => {
	if (!goodsName) return '';
	// 尝试按名称查找货品
	const goods = state.goodsList.find(item => item.goodsName === goodsName);
	if (goods) return goods.goodsCode;
	// 如果没找到，检查是否已经是编码
	const goodsByCode = state.goodsList.find(item => item.goodsCode === goodsName);
	if (goodsByCode) return goodsName; // 已经是编码，直接返回
	// 如果都没找到，可能是自定义的名称，保持原值
	return goodsName;
};

// 根据仓库编码或ID获取仓库名称
const getWarehouseName = (warehouseIdOrCodeOrName: string) => {
	if (!warehouseIdOrCodeOrName) return '';
	// 先尝试按wareCode匹配
	let warehouse = state.warehouseList.find(w => w.wareCode === warehouseIdOrCodeOrName);
	// 如果没找到，尝试按ID匹配
	if (!warehouse) {
		warehouse = state.warehouseList.find(w => w.id?.toString() === warehouseIdOrCodeOrName);
	}
	// 如果还没找到，尝试按wareName匹配（兼容旧数据）
	if (!warehouse) {
		warehouse = state.warehouseList.find(w => w.wareName === warehouseIdOrCodeOrName);
	}
	return warehouse ? warehouse.wareName : warehouseIdOrCodeOrName;
};

// 根据仓库名称获取仓库编码或ID
const getWarehouseCodeOrId = (warehouseName: string) => {
	if (!warehouseName) return '';
	const warehouse = state.warehouseList.find(w => w.wareName === warehouseName);
	// 优先返回wareCode，如果没有则返回ID
	return warehouse ? (warehouse.wareCode || warehouse.id?.toString()) : warehouseName;
};

// 打开弹窗
const openDialog = async (row: any, title: string) => {
	state.title = title;
	row = row ?? {  };
	state.ruleForm = row.id ? await systransferorderApi.detail(row.id).then(res => res.data.result) : JSON.parse(JSON.stringify(row));
	
	// 如果是编辑，将仓库编码/ID转换为名称显示
	if (state.ruleForm.fromWarehouse) {
		state.ruleForm.fromWarehouse = getWarehouseName(state.ruleForm.fromWarehouse);
	}
	if (state.ruleForm.toWarehouse) {
		state.ruleForm.toWarehouse = getWarehouseName(state.ruleForm.toWarehouse);
	}
	// goodsName字段已经存储名称，无需转换
	// 但为了兼容可能存储编码的旧数据，还是调用转换函数
	if (state.ruleForm.goodsName) {
		state.ruleForm.goodsName = getGoodsNameByCode(state.ruleForm.goodsName);
	}
	
	state.showDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emit("reloadTable");
	state.showDialog = false;
};

// 提交
const submit = async () => {
	ruleFormRef.value.validate(async (isValid: boolean, fields?: any) => {
		if (isValid) {
			let values = { ...state.ruleForm };
			
			// 将仓库名称转换回编码或ID保存
			if (values.fromWarehouse) {
				values.fromWarehouse = getWarehouseCodeOrId(values.fromWarehouse);
			}
			if (values.toWarehouse) {
				values.toWarehouse = getWarehouseCodeOrId(values.toWarehouse);
			}
			// goodsName字段保存名称，不需要转换
			// 保持用户选择的货品名称直接保存
			
			await systransferorderApi[state.ruleForm.id ? 'update' : 'add'](values);
			closeDialog();
		} else {
			ElMessage({
				message: `表单有${Object.keys(fields).length}处验证失败，请修改后再提交`,
				type: "error",
			});
		}
	});
};

//将属性或者函数暴露给父组件
defineExpose({ openDialog });
</script>
<template>
	<div class="systransferorder-container">
		<el-dialog v-model="state.showDialog" :width="800" draggable :close-on-click-modal="false">
			<template #header>
				<div style="color: #fff">
					<span>{{ state.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto" :rules="rules">
				<el-row :gutter="35">
					<el-form-item v-show="false">
						<el-input v-model="state.ruleForm.id" />
					</el-form-item>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="调拨单号" prop="code">
							<el-input v-model="state.ruleForm.code" placeholder="请输入调拨单号" maxlength="64" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="单据状态" prop="documentStatus">
							<g-sys-dict v-model="state.ruleForm.documentStatus" code="DocumentStatusEnum" render-as="select" placeholder="请选择单据状态" clearable filterable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="调拨申请日期" prop="applyDate">
							<el-date-picker v-model="state.ruleForm.applyDate" type="date" placeholder="调拨申请日期" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
					<el-form-item label="调出仓库" prop="fromWarehouse">
						<el-select v-model="state.ruleForm.fromWarehouse" placeholder="请选择调出仓库" clearable filterable>
							<el-option
								v-for="item in state.warehouseList"
								:key="item.id"
								:label="item.wareName"
								:value="item.wareName"
							/>
						</el-select>
					</el-form-item>
				</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
					<el-form-item label="调入仓库" prop="toWarehouse">
						<el-select v-model="state.ruleForm.toWarehouse" placeholder="请选择调入仓库" clearable filterable>
							<el-option
								v-for="item in state.warehouseList"
								:key="item.id"
								:label="item.wareName"
								:value="item.wareName"
							/>
						</el-select>
					</el-form-item>
				</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="出库状态" prop="outStatus">
							<g-sys-dict v-model="state.ruleForm.outStatus" code="DocumentStatusEnum" render-as="select" placeholder="请选择出库状态" clearable filterable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="入库状态" prop="inStatus">
							<g-sys-dict v-model="state.ruleForm.inStatus" code="DocumentStatusEnum" render-as="select" placeholder="请选择入库状态" clearable filterable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="调拨数量" prop="transferQuantity">
							<el-input-number v-model="state.ruleForm.transferQuantity" placeholder="请输入调拨数量" clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="调拨金额" prop="transferAmount">
							<el-input-number v-model="state.ruleForm.transferAmount" placeholder="请输入调拨金额" clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="经办人" prop="agentName">
							<el-input v-model="state.ruleForm.agentName" placeholder="请输入经办人" maxlength="64" show-word-limit clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
					<el-form-item label="调拨货品" prop="goodsName">
						<el-select v-model="state.ruleForm.goodsName" placeholder="请选择调拨货品" clearable filterable>
							<el-option
								v-for="item in state.goodsList"
								:key="item.goodsCode"
								:label="item.goodsName"
								:value="item.goodsName"
							/>
						</el-select>
					</el-form-item>
				</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.ruleForm.remark" placeholder="请输入备注" maxlength="512" show-word-limit clearable />
						</el-form-item>
					</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" >
						<el-form-item label="软删除时间" prop="deleteTime">
							<el-date-picker v-model="state.ruleForm.deleteTime" type="date" placeholder="软删除时间" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="() => state.showDialog = false">取 消</el-button>
					<el-button @click="submit" type="primary" v-reclick="1000">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<style lang="scss" scoped>
:deep(.el-select), :deep(.el-input-number) {
  width: 100%;
}
</style>